package utils
{
	import flash.net.SharedObject;
	import flash.system.Capabilities;
	import flash.system.Security;
	import flash.system.SecurityPanel;
	import flash.system.System;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;

	public class LocalCache
	{
		private static var _instance:LocalCache;
		private static var _shareObject:SharedObject;
		private static  var  _publicShareObject:SharedObject;
		public function LocalCache(uid:String)
		{
			if(_instance){
			    throw new Error("单例");
			}
			_shareObject=SharedObject.getLocal("$FY_WEBGAME_2012"+uid+"$");
			_publicShareObject=SharedObject.getLocal("$FY_WEBGAME_2012_RES$");
		
			if(_publicShareObject.data.hasOwnProperty("res")){
				resDic=_publicShareObject.data.res;
			}else{
				resDic=new Dictionary();
				_publicShareObject.data.res=resDic;
			}
		}
		private var _isCacheRes:Boolean;
		public function get isCacheRes():Boolean
		{
			return _isCacheRes;
		}

		public function set isCacheRes(value:Boolean):void{
			_isCacheRes=value;
			if(!value){
				delete _publicShareObject.data.res;
				_publicShareObject.flush();
			}
		}
		
		public function clear():void{
			_shareObject.clear();
		}
		private var resDic:Object;
		
		private var maxSize:Number=1024*1024*50
		/**
		 * 暂时没有考虑文件版本问题，后面必须考虑。
		 * //todo:
		 */
		public function addRes(id:String,data:*):void{
			if(!_isCacheRes) return;
			if(resDic.hasOwnProperty(id)) return;
			resDic[id]=data;
			_publicShareObject.data.res=resDic;
			_publicShareObject.flush(maxSize);
		}
		public function getRes(id:String):ByteArray{
			if(resDic.hasOwnProperty(id)){
		       return resDic[id] as ByteArray;
			}
			return null;
		}
		public static function getInstance(uid:String="0"):LocalCache{
		   if(_instance==null){
		      _instance=new LocalCache(uid);
		   }
		   return _instance;
		}
		
		public function remove(key:*):void{
			_shareObject.data[key]=null;
			delete _shareObject.data[key];
			_shareObject.flush();
		}
		
		public function pushData(key:*,data:*):void{
			_shareObject.data[key]=data;
			trace("共享对象:",_shareObject.size);
		}
		
		public function flush():void{
			_shareObject.flush();
		}

		public function getData(key:*):*{
			 return _shareObject.data[key];
		}
		
		public function hasData(key:*):Boolean{
		    return _shareObject.data.hasOwnProperty(key);
		}
	}
}